package com.item.action;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.base.Page;
import com.base.dialect.PaginationSupport;
import com.base.util.JSONUtils;
import com.base.util.StringUtil;
import com.item.dao.model.Type;
import com.item.dao.model.TypeExample;
import com.item.exception.JSONRepUtils;
import com.item.service.TypeService;

@Controller
public class TypeController {
	@Autowired
	private TypeService typeService;
	
	@RequestMapping("/listType")
	@ResponseBody
	public String list(Page param, Type type, Integer isNotPage, Integer isM) throws Exception{
		Object objForSer = null;
		TypeExample example = new TypeExample();
		PaginationSupport.setContext(param.getPageStart(), param.getPageSize(), null);
		TypeExample.Criteria criteria = example.createCriteria();
		
		if(StringUtils.isNotBlank(type.getPid())) {
			criteria.andPidEqualTo(type.getPid());
		}
		example.setOrderByClause("code ASC");
		List<Type> list = typeService.selectByExample(example);
		if(isNotPage != null && isNotPage == 1) {
			objForSer = list;
		} else {
			objForSer = new Page(PaginationSupport.getContext().getTotalCount(), list);
		}
		
		return JSONRepUtils.serialize(objForSer, isM);
	}
	
	@RequestMapping("/showlistType")
	public String list() {
		return "type/typeList";
	}
	
	@RequestMapping("/toEditType")
	public String toEdit()throws Exception{
		return "type/typeEdit";
	}
	
	@RequestMapping(value="/saveType")
	@ResponseBody
	public String save(Type type, Integer isTop, HttpSession session) throws Exception{		
		try{
			if(StringUtil.isEmpty(type.getId())){
				type.setCode(typeService.getLeastCode());
				
				type.setCreateTime(new Date());
				typeService.insertSelective(type);
			} else {
				type.setModifyTime(new Date());
				typeService.updateByPrimaryKeySelective(type);
			}
		}catch(Exception e){
			e.printStackTrace();
			return "{\"success\":false}";
		}
		
		return "{\"success\":true}";
	}
	
	@RequestMapping(value="/findByIdType")
	@ResponseBody
	public String findById(String id,HttpSession session)throws Exception{		
		Type n = typeService.selectByPrimaryKey(id);

		return JSONUtils.serialize(n);
	}
	
	@RequestMapping("/delType")
	@ResponseBody
	public String del(String id,String url,HttpSession session)throws Exception{
		String[] ids = id.split(",");
		int len = ids.length;
		for(int i = 0; i < len; i++) {
			typeService.deleteByPrimaryKey(ids[i]);
		}
		return "{\"success\":true}";
	}
	
	
}

